suppressWarnings(library(R2HTML))
suppressWarnings(library(lattice))
suppressWarnings(library(sciplot))
suppressWarnings(library(plotrix))

# retrieve args
Args <- commandArgs(TRUE)

#Read in data
statdata <- read.csv(Args[3], header=TRUE, sep=",")

#Copy Args
XAxisVar <- Args[4]
XAxisTransform <- Args[5]
YAxisVars <- Args[6]
YAxisTransform <- Args[7]
FirstCatFactor <- Args[8]
SecondCatFactor <- Args[9]
GraphStyle <- Args[10]
MainTitle <- Args[11]
XAxisTitle <- Args[12]
XAxisTitleHist <- Args[12]
YAxisTitle <- Args[13]
ScatterPlot <- Args[14]
LinearFit <- Args[15]
CorrelationPValue <- Args[16]
BoxPlot <- Args[17]
Outliers <- Args[18]
SEMPlot <- Args[19]
SEMPlotType <- Args[20]
HistogramPlot <- Args[21]
NormalDistFit <- Args[22]
CaseProfilesPlot <- Args[23]
CaseIDFactor <- Args[24]
ReferenceLine <- Args[25]
DisplayLegend <-Args[26]

#Setup the html file and associated css file
htmlFile <- sub(".csv", ".html", Args[3]); #determine the file name of the html file
.HTML.file = htmlFile
cssFile <- "r2html.css"
cssFile <- paste("'",cssFile,"'", sep="") #need to enclose in quotes when path has spaces in it
HTMLCSS(CSSfile = cssFile)

#Output HTML header
HTML.title("<bf>SilveR Graphics", HR=1, align="left")

#Set up titles
if (MainTitle == "NULL")
{
	MainTitle = ""
}

if (XAxisTitleHist == "NULL")
{
	XAxisTitleHist = YAxisVars
} 

if (XAxisTitle == "NULL")
{
	XAxisTitle = XAxisVar
}

if (YAxisTitle == "NULL")
{
	YAxisTitle = YAxisVars
}



#Removing illegal charaters

# Bug fix Aug 2010 (STB)
# CPXAxisTitle <-XAxisVar
  CPXAxisTitle <-XAxisTitle

for (i in 1:10)
{
# Additional characters included Aug 2010 (STB)
YAxisTitle<-sub("ivs_tilde_ivs"	,"~", YAxisTitle) 
YAxisTitle<-sub("ivs_star_ivs"	,"*", YAxisTitle) 
YAxisTitle<-sub("ivs_plus_ivs"	,"+", YAxisTitle) 

YAxisTitle<-sub("ivs_sp_ivs"	," ", YAxisTitle) 
YAxisTitle<-sub("ivs_ob_ivs"	,"(", YAxisTitle) 
YAxisTitle<-sub("ivs_cb_ivs"	,")", YAxisTitle) 
YAxisTitle<-sub("ivs_div_ivs"	,"/", YAxisTitle) 
YAxisTitle<-sub("ivs_pc_ivs"	,"%", YAxisTitle) 
YAxisTitle<-sub("ivs_hash_ivs"	,"#", YAxisTitle) 
YAxisTitle<-sub("ivs_pt_ivs"	,".", YAxisTitle) 
YAxisTitle<-sub("ivs_hyphen_ivs","-", YAxisTitle) 
YAxisTitle<-sub("ivs_at_ivs"	,"@", YAxisTitle) 
YAxisTitle<-sub("ivs_colon_ivs"	,":", YAxisTitle) 
YAxisTitle<-sub("ivs_exclam_ivs","!", YAxisTitle) 
YAxisTitle<-sub("ivs_quote_ivs"	,"`", YAxisTitle) 
YAxisTitle<-sub("ivs_pound_ivs"	,"£", YAxisTitle) 
YAxisTitle<-sub("ivs_dollar_ivs","$", YAxisTitle) 
YAxisTitle<-sub("ivs_hat_ivs"	,"^", YAxisTitle) 
YAxisTitle<-sub("ivs_amper_ivs"	,"&", YAxisTitle) 
YAxisTitle<-sub("ivs_obrace_ivs","{", YAxisTitle) 
YAxisTitle<-sub("ivs_cbrace_ivs","}", YAxisTitle) 
YAxisTitle<-sub("ivs_semi_ivs"	,";", YAxisTitle) 
YAxisTitle<-sub("ivs_pipe_ivs"	,"|", YAxisTitle)
YAxisTitle<-sub("ivs_slash_ivs"	,"\\",YAxisTitle) 
YAxisTitle<-sub("ivs_osb_ivs"	,"[", YAxisTitle) 
YAxisTitle<-sub("ivs_csb_ivs"	,"]", YAxisTitle) 
YAxisTitle<-sub("ivs_eq_ivs"	,"=", YAxisTitle) 
YAxisTitle<-sub("ivs_lt_ivs"	,"<", YAxisTitle) 
YAxisTitle<-sub("ivs_gt_ivs"	,">", YAxisTitle) 
YAxisTitle<-sub("ivs_dblquote_ivs"	,"\"", YAxisTitle) 

# Additional characters included Aug 2010 (STB)
XAxisTitle<-sub("ivs_tilde_ivs"	,"~", XAxisTitle) 
XAxisTitle<-sub("ivs_star_ivs"	,"*", XAxisTitle) 
XAxisTitle<-sub("ivs_plus_ivs"	,"+", XAxisTitle) 

XAxisTitle<-sub("ivs_sp_ivs"	," ", XAxisTitle) 
XAxisTitle<-sub("ivs_ob_ivs"	,"(", XAxisTitle) 
XAxisTitle<-sub("ivs_cb_ivs"	,")", XAxisTitle) 
XAxisTitle<-sub("ivs_div_ivs"	,"/", XAxisTitle) 
XAxisTitle<-sub("ivs_pc_ivs"	,"%", XAxisTitle) 
XAxisTitle<-sub("ivs_hash_ivs"	,"#", XAxisTitle) 
XAxisTitle<-sub("ivs_pt_ivs"	,".", XAxisTitle) 
XAxisTitle<-sub("ivs_hyphen_ivs","-", XAxisTitle) 
XAxisTitle<-sub("ivs_at_ivs"	,"@", XAxisTitle) 
XAxisTitle<-sub("ivs_colon_ivs"	,":", XAxisTitle) 
XAxisTitle<-sub("ivs_exclam_ivs","!", XAxisTitle) 
XAxisTitle<-sub("ivs_quote_ivs"	,"`", XAxisTitle) 
XAxisTitle<-sub("ivs_pound_ivs"	,"£", XAxisTitle) 
XAxisTitle<-sub("ivs_dollar_ivs","$", XAxisTitle) 
XAxisTitle<-sub("ivs_hat_ivs"	,"^", XAxisTitle) 
XAxisTitle<-sub("ivs_amper_ivs"	,"&", XAxisTitle) 
XAxisTitle<-sub("ivs_obrace_ivs","{", XAxisTitle) 
XAxisTitle<-sub("ivs_cbrace_ivs","}", XAxisTitle) 
XAxisTitle<-sub("ivs_semi_ivs"	,";", XAxisTitle) 
XAxisTitle<-sub("ivs_pipe_ivs"	,"|", XAxisTitle) 
XAxisTitle<-sub("ivs_osb_ivs"	,"[", XAxisTitle) 
XAxisTitle<-sub("ivs_csb_ivs"	,"]", XAxisTitle) 
XAxisTitle<-sub("ivs_eq_ivs"	,"=", XAxisTitle) 
XAxisTitle<-sub("ivs_lt_ivs"	,"<", XAxisTitle) 
XAxisTitle<-sub("ivs_gt_ivs"	,">", XAxisTitle) 
XAxisTitle<-sub("ivs_slash_ivs"	,"\\",XAxisTitle) 
XAxisTitle<-sub("ivs_dblquote_ivs"	,"\"", XAxisTitle) 


# Additional characters included Aug 2010 (STB)
CPXAxisTitle<-sub("ivs_tilde_ivs"	,"~", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_star_ivs"	,"*", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_plus_ivs"	,"+", CPXAxisTitle) 

CPXAxisTitle<-sub("ivs_sp_ivs"		," ", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_ob_ivs"		,"(", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_cb_ivs"		,")", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_div_ivs"		,"/", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_pc_ivs"		,"%", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_hash_ivs"	,"#", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_pt_ivs"		,".", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_hyphen_ivs"	,"-", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_at_ivs"		,"@", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_colon_ivs"	,":", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_exclam_ivs"	,"!", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_quote_ivs"	,"“", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_pound_ivs"	,"£", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_dollar_ivs"	,"$", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_hat_ivs"		,"^", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_amper_ivs"	,"&", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_obrace_ivs"	,"{", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_cbrace_ivs"	,"}", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_semi_ivs"	,";", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_pipe_ivs"	,"|", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_slash_ivs"	,"\\", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_osb_ivs"		,"[", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_csb_ivs"		,"]", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_eq_ivs"		,"=", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_lt_ivs"		,"<", CPXAxisTitle) 
CPXAxisTitle<-sub("ivs_gt_ivs"		,">", CPXAxisTitle)  
CPXAxisTitle<-sub("ivs_dblquote_ivs"	,"\"", CPXAxisTitle) 
}
XAxisTitleHist = YAxisTitle



#Response

title<-c("Selected variables")


HTML.title(title, HR=2, align="left")


add<-c("The  variable ")
add<-paste(add, YAxisVars, sep="")
add<-paste(add, " has been selected as the response", sep="")

if(XAxisVar != "NULL")
{
add<-paste(add, " and the variable ", sep="")
add<-paste(add, XAxisVar, sep="")
add<-paste(add, " has been selected to define the X-axis", sep="")
}
add<-paste(add, ". ", sep="")



if (is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE" && YAxisTransform != "None")
{
add<-paste(add, "The variable ", sep="")
add<-paste(add, YAxisVars, sep="")
add<-paste(add, " has been ", sep="")
add<-paste(add, YAxisTransform, sep="")
add<-paste(add, " transformed.", sep="")
}

if (XAxisVar != "NULL" && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && XAxisTransform != "None")
{
add<-paste(add, " The variable ", sep="")
add<-paste(add, XAxisVar, sep="")
add<-paste(add, " has been ", sep="")
add<-paste(add, XAxisTransform, sep="")
add<-paste(add, " transformed.", sep="")
}





if (FirstCatFactor != "NULL" && SecondCatFactor == "NULL")
{
add<-paste(add, " The variable ", sep="")
add<-paste(add, FirstCatFactor, sep="")
add<-paste(add, " has been selected as the categorisation factor.", sep="")
}

if (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")
{
add<-paste(add, " The variable ", sep="")
add<-paste(add, SecondCatFactor, sep="")
add<-paste(add, " has been selected as the categorisation factor.", sep="")
}

if (FirstCatFactor != "NULL" && SecondCatFactor != "NULL")
{
add<-paste(add, " The variables ", sep="")
add<-paste(add, FirstCatFactor, sep="")
add<-paste(add, " and ", sep="")
add<-paste(add, SecondCatFactor, sep="")
add<-paste(add, " have been selected as the categorisation factors.", sep="")
}

if (CaseProfilesPlot != "N")
{
add<-paste(add, " The variable ", sep="")
add<-paste(add, CaseIDFactor, sep="")
add<-paste(add, " defines the case profiles.", sep="")
}



HTML.title("</bf> ", HR=2, align="left")
HTML.title(add, HR=0, align="left")
















#Histogram plot - y should be numerical, x not needed (message in log)!



#Titles
if(HistogramPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL")
{
	add<-c("Density histogram")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
} else if(HistogramPlot == "Y" && (FirstCatFactor != "NULL" || SecondCatFactor != "NULL"))
{
	add<-c("Categorised density histogram")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
}

#NON CATegorised HistogramPlot - categorical x
if(HistogramPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the X-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(HistogramPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#calcualting the break points
	maxresp<-max(eval(parse(text = paste("statdata$",YAxisVars))))
	minresp<-min(eval(parse(text = paste("statdata$",YAxisVars))))
	interval<-(maxresp-minresp)/10
	breq<-c(minresp)


	for (i in 2:10)
	{
		breq[i]=breq[i-1]+interval
	}
	breq[1]<-breq[2]-interval*1
	breq[11]<-breq[10]+interval*1

	#Plot
	nchistplot <- sub(".html", "nchistplot.jpg", htmlFile)
	jpeg(nchistplot)
	if (NormalDistFit=="N")
	{
		par(las=1)
		histogram(~eval(parse(text = paste("statdata$", YAxisVars))), type="density", main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density", col = "grey", breaks=breq) 
	} else {
		par(las=1)	
		histogram(~eval(parse(text = paste("statdata$", YAxisVars))), type="density", main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density", col = "grey" , breaks=breq, panel = function(x, ...) 
		{
      		panel.histogram(x, ...)
       		panel.mathdensity(dmath = dnorm, col = "black", args = list(mean=mean(x),sd=sd(x)))
		}
		)
	}
}
if(HistogramPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nchistplot), Align="centre")
}

# ONE CAT - seperate,  categorial x
if(HistogramPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the X-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(HistogramPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#calcualting the break points
	maxresp<-max(eval(parse(text = paste("statdata$",YAxisVars))))
	minresp<-min(eval(parse(text = paste("statdata$",YAxisVars))))
	interval<-(maxresp-minresp)/10
	breq<-c(minresp)
	for (i in 2:10)
	{
		breq[i]=breq[i-1]+interval
	}
	breq[1]<-breq[2]-interval*1
	breq[11]<-breq[10]+interval*1

	#Plot
	nchistplot <- sub(".html", "nchistplot.jpg", htmlFile)
	jpeg(nchistplot)
	if (NormalDistFit=="N")
	{
		par(las=1)
		histogram( ~ eval(parse(text = paste("statdata$", YAxisVars)))|as.factor(statdata$catfact), strip = strip.custom(style=1, bg="grey95"), type="density", main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density", breaks=breq, col = "grey", panel = function(x, ...) 	{
        																      	panel.histogram(x, ...)
              																	} )
	} else {
		par(las=1)
		histogram( ~ eval(parse(text = paste("statdata$", YAxisVars)))|as.factor(statdata$catfact), strip = strip.custom(style=1, bg="grey95"), type="density", main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density", breaks=breq, col = "grey", panel = function(x, ...) 	{
        																      	panel.histogram(x, ...)
              																	panel.mathdensity(dmath = dnorm, col = "black",
                               															args = list(mean=mean(x),sd=sd(x)))
		}
		)
	}
}
if(HistogramPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL") ) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nchistplot), Align="centre")
}

# ONE/Two CAT - overlaid,  categorial x
if(HistogramPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the X-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(HistogramPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	nofact<-length(unique(levels(as.factor(  statdata$catfact))))
	together<-(length(unique(levels(as.factor(statdata$catfact))))+1)*10

	#calcualting the break points
	maxresp<-max(eval(parse(text = paste("statdata$",YAxisVars))))
	minresp<-min(eval(parse(text = paste("statdata$",YAxisVars))))
	interval<-(maxresp-minresp)/10
	breq<-c(minresp)
	for (i in 2:10)
	{
		breq[i]=breq[i-1]+interval
	}
	breq[1]<-breq[2]-interval*1
	breq[11]<-breq[10]+interval*1

	#Plot
	nchistplot <- sub(".html", "nchistplot.jpg", htmlFile)
	jpeg(nchistplot)

	aa<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[1])
	aar<-eval(parse(text = paste("aa$", YAxisVars)))
	aaymax<-max(hist(aar,freq=FALSE,breaks=breq)$density)
	ymax<-aaymax
	yaxis<-ymax + ymax*length(unique(levels(as.factor(statdata$catfact))))*0.05
	
	if (nofact>1)
	{
		ab<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[2])
		abr<-eval(parse(text = paste("ab$", YAxisVars)))
		l <- list(aar,abr) 
		abymax<-max(hist(abr,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}

		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey0","grey85")   )
			axis(side=1, labels=FALSE )
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, xlim=c(0,together), ylim=c(0,ymax), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			axis(side=1, labels=FALSE )
		}
	}

	if (nofact>2)
	{
		ac<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[3])
		acr<-eval(parse(text = paste("ac$", YAxisVars)))
		l <- list(aar,abr,acr) 
		acymax<-max(hist(acr,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey0","grey65","grey85")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,ymax), main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>3)
	{
		ad<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[4])
		adr<-eval(parse(text = paste("ad$", YAxisVars)))
		l <- list(aar,abr,acr,adr) 
		adymax<-max(hist(adr,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax,adymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey0","grey64","grey84","grey97")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE,ylim=c(0,ymax),main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>4)
	{
		ae<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[5])
		aer<-eval(parse(text = paste("ae$", YAxisVars)))
		l <- list(aar,abr,acr,adr,aer) 
		aeymax<-max(hist(aer,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax,adymax,aeymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq,axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey21","grey36","grey64","grey83","grey95")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE,ylim=c(0,ymax), main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>5)
	{
		af<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[6])
		afr<-eval(parse(text = paste("af$", YAxisVars)))
		l <- list(aar,abr,acr,adr,aer,afr) 
		afymax<-max(hist(afr,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax,adymax,aeymax,afymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey21","grey30","grey45","grey70","grey83","grey95")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE,ylim=c(0,ymax), main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>6)
	{
		ag<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[7])
		agr<-eval(parse(text = paste("ag$", YAxisVars)))
		l <- list(aar,abr,acr,adr,aer,afr,agr) 
		agymax<-max(hist(agr,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax,adymax,aeymax,afymax,agymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))	
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey21","grey30","grey50","grey69","grey80","grey90","grey97")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE,ylim=c(0,ymax), main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>7)
	{
		ah<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[8])
		ahr<-eval(parse(text = paste("ah$", YAxisVars)))
		l <- list(aar,abr,acr,adr,aer,afr,agr,ahr) 
		ahymax<-max(hist(ahr,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax,adymax,aeymax,afymax,agymax,ahymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey21","grey30","grey48","grey58","grey68","grey78","grey88","grey98")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE,ylim=c(0,ymax), main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>8)
	{
		ai<-subset(statdata, statdata$catfact == unique(levels(as.factor(statdata$catfact)))[9])
		air<-eval(parse(text = paste("ai$", YAxisVars)))
		l <- list(aar,abr,acr,adr,aer,afr,agr,ahr,air) 
		aiymax<-max(hist(air,freq=FALSE,breaks=breq)$density)
		ymax2<-max(aaymax,abymax,acymax,adymax,aeymax,afymax,agymax,ahymax,aiymax)
		yaxis2<-ymax2 + ymax2*length(unique(levels(as.factor(statdata$catfact))))*0.05
		if (yaxis2<2) {yaxis=2}	else {yaxis=yaxis2}
		if (ymax2<2) {ymax=2}	else {ymax=ymax2}
		if(DisplayLegend=="Y")
		{
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE, ylim=c(0,yaxis),xlim=c(0,together), main=MainTitle, xlab=XAxisTitleHist, 	ylab = "Density")
			axis(at=0:yaxis, side=2,labels = TRUE,par(las=1))		
			legend("topright", legend=levels(as.factor(statdata$catfact)),cex=0.6, bg="white",fill=c("grey21","grey30","grey40","grey50","grey60","grey70","grey79","grey88","grey97")   )
			axis(side=1, labels=FALSE)
		} else {
			par(las=1)
			multhist(l, freq=FALSE, breaks=breq, axes=FALSE,ylim=c(0,ymax), main=MainTitle,xlim=c(0,together), xlab=XAxisTitleHist, 	ylab = "Density")
			axis(side=1, labels=FALSE)
			axis(at=0:ymax, side=2,labels = TRUE,par(las=1))
		}
	}

	if (nofact>9)
	{
		HTML.title("<bf> ", HR=2, align="left")
		HTML.title("<bf>   Unfortunately there are greater than 9 levels of the categorisation factors. It is recommended that the Separate option in selected instead.", HR=0, align="left")
	}

	if (NormalDistFit=="Y")
	{
		HTML.title("<bf> ", HR=2, align="left")
		add<-c("The normal distribution fit is not supported with the Overlaid option, please use the Separate option instead.")
		

		HTML.title(add, HR=0, align="left")
	}
}
	
if(HistogramPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	if (length(unique(levels(as.factor(statdata$catfact))))<10)
	{
		void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nchistplot), Align="centre")
	}
}

# TWO CAT - seperate,  categorial x
if(HistogramPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the X-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(HistogramPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#calcualting the break points
	maxresp<-max(eval(parse(text = paste("statdata$",YAxisVars))))
	minresp<-min(eval(parse(text = paste("statdata$",YAxisVars))))
	interval<-(maxresp-minresp)/10
	breq<-c(minresp)
	for (i in 2:10)
	{
		breq[i]=breq[i-1]+interval
	}
	breq[1]<-breq[2]-interval*1
	breq[11]<-breq[10]+interval*1

	#Plot
	nchistplot <- sub(".html", "nchistplot.jpg", htmlFile)
	jpeg(nchistplot)
	if (NormalDistFit=="N")
	{
		par(las=1)
		histogram( ~ eval(parse(text = paste("statdata$", YAxisVars)))|as.factor(eval(parse(text = paste("statdata$", FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$",SecondCatFactor)))), strip = strip.custom(style=1, bg="grey95"), type="density", main=MainTitle, xlab=XAxisTitleHist, breaks=breq,	ylab = "Density", col = "grey", panel = function(x, ...) 	{
        																      	panel.histogram(x, ...)
              																	} )
	} else {
		par(las=1)
		histogram( ~ eval(parse(text = paste("statdata$", YAxisVars)))|as.factor(eval(parse(text = paste("statdata$", FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$",SecondCatFactor)))), strip = strip.custom(style=1, bg="grey95"), type="density", main=MainTitle, xlab=XAxisTitleHist, breaks=breq,	ylab = "Density", col = "grey", panel = function(x, ...) 	{
        																      	panel.histogram(x, ...)
              																	panel.mathdensity(dmath = dnorm, col = "black",
                               															args = list(mean=mean(x),sd=sd(x)))
          																	} )
	}
}
if(HistogramPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nchistplot), Align="centre")
}










#Means with SEM plot - y should be numerical, x should be categorical

#Titles
if(SEMPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL" && YAxisVars != "NULL")
{
	add<-c("Observed means with standard errors plot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
} else if(SEMPlot == "Y" && (FirstCatFactor != "NULL" || SecondCatFactor != "NULL") && YAxisVars != "NULL")
{
	add<-c("Categorised observed means with standard errors plot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
}

#NON CATegorised SEMPlot - categorical x
if(SEMPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE )
{
		HTML.title("<bf> ", HR=2, align="left")
		add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
		

		HTML.title(add, HR=0, align="left")
}
if(SEMPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE )
{
	#Plot
	ncSEMPlot <- sub(".html", "ncSEMPlot.jpg", htmlFile)
	jpeg(ncSEMPlot)
	yaxis<- ceiling(max(unlist(lapply(split(eval(parse(text = paste("statdata$", YAxisVars))), eval(parse(text = paste("statdata$", XAxisVar)))),mean)))+2*sqrt(max(unlist(lapply(split(eval(parse(text = paste("statdata$", YAxisVars))), eval(parse(text = paste("statdata$", XAxisVar)))),var)))/ min(unlist(lapply(split(eval(parse(text = paste("statdata$", YAxisVars))), eval(parse(text = paste("statdata$", XAxisVar)))),length)))))

	#Calculating the yaxis max value
	test<-bargraph.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))))
	selev<-c(0)
	semean<-c(0)
	semean2<-c(0)
	avemean<-c(0)

	for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
	{
		tempdata2<-subset(statdata,as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) == unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i])
		selev[i]=se(eval(parse(text = paste("tempdata2$", YAxisVars))), na.rm=TRUE)
	}
	for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
	{
		semean[i]=test$vals[i]+selev[i]
		semean2[i]=test$vals[i]-selev[i]
		avemean[i]=test$vals[i]
	}
	yaxis<-max(semean,na.rm=TRUE)*1.1
	yaxis2<-min(semean2,na.rm=TRUE)*1.1
	yaxis3<-min(semean,na.rm=TRUE)*1.1
	maxmean<-max(avemean,na.rm=TRUE)
	minmean<-min(avemean,na.rm=TRUE)

	if (SEMPlotType =="ColumnPlot" && maxmean<0)
	{
		bargraph.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))), uc=FALSE, legend=TRUE, ncol=1,xlim=c(0, length(unique(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))*1.2), ylim=c(yaxis2,0), main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05)
		axis(side=1, labels=FALSE, pos=0, tck=0)
		axis(side=2, labels=TRUE, pos=0)
	} else if (SEMPlotType =="ColumnPlot" && maxmean>=0 && minmean>=0)
	{
		par(las=1) 
		bargraph.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))), lc=FALSE, legend=TRUE, ncol=1,xlim=c(0, length(unique(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))*1.2),ylim=c(0, yaxis), main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05)
		axis(side=1, labels=FALSE, pos=0, tck=0)
		axis(side=2, labels=TRUE, pos=0)
	} else if (SEMPlotType =="ColumnPlot" && maxmean>=0 && minmean<=0)
	{
		par(las=1) 
		bargraph.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))), lc=TRUE, legend=TRUE, ncol=1,xlim=c(0, length(unique(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))*1.2),ylim=c(yaxis2, yaxis), main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05)
		abline=0
		axis(side=1, labels=FALSE, pos=0, tck=0)
		axis(side=2, labels=TRUE, pos=0)
	} 
	else
	{
		par(las=1) 
		lineplot.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))),  legend=TRUE, ncol=1, main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle,  cex=2, err.width=0.05) #,axes=TRUE,)
	}
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncSEMPlot), Align="centre")
}

# ONE CAT - seperate,  categorial x
if(SEMPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL") ) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}

if(SEMPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL") ) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	selev<-c(0)
	semean<-c(0)
	semean2<-c(0)
	avemean<-c(0)

	k<-1

	for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
	{
		tempdata2<-subset(statdata,as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) == unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i])
		for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))
		{
			tempdata3<-subset(tempdata2,as.factor(tempdata2$catfact) == unique(levels(as.factor(tempdata2$catfact)))[j])

			if(dim(tempdata3)[1]==0)
			{
				selev[k]=NA
				semean[k]<-NA
				semean2[k]<-NA
				avemean[k]<-0
			} else 
			{
				if (length(unique(eval(parse(text = paste("tempdata3$", YAxisVars)))))==1)
				{
					selev[k]=0
					semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
				} else 
				{
					selev[k]=se(eval(parse(text = paste("tempdata3$", YAxisVars))), na.rm=TRUE)
					semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))+selev[k]
					semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))-selev[k]
					avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
				}
			}
			k=k+1
		}
	}

	#Calculating the yaxis max value
	maxresp<-max(semean, na.rm=TRUE)
	minresp<-0
	miniresp<-min(semean2, na.rm=TRUE)
	rangeresp<-maxresp-minresp
	yaxis<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact))))*0.05

	maxresp2<-min(semean2, na.rm=TRUE)
	minresp<-0
	rangeresp2<- maxresp2
	yaxis2<-maxresp2 + rangeresp2*length(unique(levels(as.factor(statdata$catfact))))*0.05

	#creating the new dataset
	a<-1
	b<-1
	c<-1
	t<-1
	yax<-c(0)
	xax<-c(0)
	fcat<-(0)	
	means<-c(0)
	te<-c(0)

	upper<-semean
	lower<-semean2

	maxmean<-max(avemean,na.rm=TRUE)
	minmean<-min(avemean,na.rm=TRUE)

	for (w in 1:51)
	{
		for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))	
			{
				yax[a]=te[1]
				xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
				fcat[a]=unique(levels(as.factor(  statdata$catfact   )))[j]		
				a=a+1		
			}
		}
	}
	for (w in 1:50)
	{
		for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))	
			{
				yax[a]=avemean[c]
				xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
				fcat[a]=unique(levels(as.factor(  statdata$catfact   )))[j]		
				a=a+1	
				c=c+1	
			}
		}
		c=1
	}

	for (j in 1:(length(unique(levels(as.factor(  statdata$catfact))))*length(unique(levels(as.factor( eval(parse(text = paste("statdata$", XAxisVar)))    )))))	)
	{
	
		if (avemean[j]>0)
		{
			yax[j+a-1]=upper[j]
		} else
		{
			yax[j+a-1]=lower[j]
		}

	}

	for (i in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", XAxisVar)))   )))))	
	{
		for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))	
		{
			xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
			fcat[a]=unique(levels(as.factor(  statdata$catfact   )))[j]		
			a=a+1
		b=b+1		
		}
	}
	yax2<-as.numeric(yax)
	tempdata3<-data.frame(yax2,xax,fcat)

	#Plot
	ncSEMPlot <- sub(".html", "ncSEMPlot.jpg", htmlFile)
	jpeg(ncSEMPlot)
	if (SEMPlotType =="ColumnPlot")
	{
		if (maxmean >0 && minmean >=0)
		{
			par(las=1) 
			suppressWarnings(bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(te[1],yaxis),))
		} else if (maxmean <=0 && minmean <0)
		{
			par(las=1) 
			suppressWarnings(bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(yaxis2,0)))
		} else if (maxmean >0 && minmean <0)
		{
			par(las=1) 
			suppressWarnings(p<-bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")) , coef=0, fill="grey", col=NA, ylim=c(yaxis2,yaxis)))
			update(p, panel=function(...)
			{
		   		panel.bwplot(...)
   				panel.abline(h=0, col="black", lty=1, lwd=1)
			})
		} 
	} else 
	{	
		HTML.title("<bf> ", HR=2, align="left")
		HTML.title("<bf> The separate option is not currently available for the SEM line plot. Use the overlaid option instead.", HR=0, align="left")
	}
}


if(SEMPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate"&& SEMPlotType =="ColumnPlot" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncSEMPlot), Align="centre")
}


# ONE CAT - overlaid,  categorial x

if(SEMPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(SEMPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	lines<-c(1:length(unique(levels(as.factor(statdata$catfact)))))

	#Plot
	ncSEMPlot <- sub(".html", "ncSEMPlot.jpg", htmlFile)
	jpeg(ncSEMPlot)

	#Calculating the yaxis max value
	selev<-c(0)
	semean<-c(0)
	semean2<-c(0)
	avemean<-c(0)

	k<-1

	for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
	{
		tempdata2<-subset(statdata,as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) == unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i])
		for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))
		{
			tempdata3<-subset(tempdata2,as.factor(tempdata2$catfact) == unique(levels(as.factor(tempdata2$catfact)))[j])

			if(dim(tempdata3)[1]==0)
			{
				selev[k]=NA
				semean[k]<-NA
				semean2[k]<-NA
				avemean[k]<-0
			} else 
			{
				if (length(unique(eval(parse(text = paste("tempdata3$", YAxisVars)))))==1)
				{
					selev[k]=0
					semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
				} else 
				{
					selev[k]=se(eval(parse(text = paste("tempdata3$", YAxisVars))), na.rm=TRUE)
					semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))+selev[k]
					semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))-selev[k]
					avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
				}
			}
			k=k+1
		}
	}

	maxresp<-max(semean, na.rm=TRUE)
	maxresp2<-min(semean2, na.rm=TRUE)
	minresp<-0
	rangeresp<-maxresp-minresp
	yaxis<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact)))) * 0.05
	rangeresp2<-maxresp2
	yaxis2<-maxresp2 + rangeresp2*length(unique(levels(as.factor(statdata$catfact)))) * 0.05


	maxmean<-max(avemean,na.rm=TRUE)
	minmean<-min(avemean,na.rm=TRUE)
	statdata2<-statdata

	if ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL"))
	{
		statdata2[1] = eval(parse(text = paste("statdata$", YAxisVars)))
		statdata2[2] = eval(parse(text = paste("statdata$", XAxisVar)))
		statdata2[3] = statdata$catfact

		if (FirstCatFactor != "NULL")
		{
			statdata2[4] = eval(parse(text = paste("statdata$", FirstCatFactor)))
		} else 
		{
		statdata2[4] = eval(parse(text = paste("statdata$", SecondCatFactor)))
		}
		if (dim(statdata2)[2]==5)
		{
			statdata2[5] = eval(parse(text = paste("statdata$", CaseIDFactor)))
		}
		if (dim(statdata2)[2]==4 && FirstCatFactor != "NULL")
		{
			nams<-c(eval(YAxisVars),eval(XAxisVar), "catfact", eval(FirstCatFactor))
		}
		if (dim(statdata2)[2]==4 && SecondCatFactor != "NULL")
		{
			nams<-c(eval(YAxisVars),eval(XAxisVar), "catfact", eval(SecondCatFactor))
		}
		if (dim(statdata2)[2]==5 && FirstCatFactor != "NULL")
		{
			nams<-c(eval(YAxisVars),eval(XAxisVar), "catfact", eval(FirstCatFactor),eval(CaseIDFactor))
		}
		if (dim(statdata2)[2]==5 && SecondCatFactor != "NULL")
		{
			nams<-c(eval(YAxisVars),eval(XAxisVar), "catfact", eval(SecondCatFactor),eval(CaseIDFactor))
		}
		
		colnames(statdata2)<-nams
		k<-dim(statdata2)[1]+1

		for (i in 1 : length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			for (j in 1 : length(unique(levels(as.factor(statdata$catfact)))))
			{
				statdata2[k,2] = levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar)))))[i]
				statdata2[k,3] = levels(as.factor(statdata$catfact))[j]
				statdata2[k,4] = levels(as.factor(statdata$catfact))[j]
				k=k+1
			} 
		}
	}

	if (FirstCatFactor != "NULL" && SecondCatFactor != "NULL")
	{
		statdata2[1] = eval(parse(text = paste("statdata$", YAxisVars)))
		statdata2[2] = eval(parse(text = paste("statdata$", XAxisVar)))
		statdata2[3] = eval(parse(text = paste("statdata$", FirstCatFactor)))
		statdata2[4] = eval(parse(text = paste("statdata$", SecondCatFactor)))
		statdata2[5] = statdata$catfact
		if (dim(statdata2)[2]==6)
		{
			statdata2[6] = eval(parse(text = paste("statdata$", CaseIDFactor)))
		}

		if (dim(statdata2)[2]==5)
		{
			nams<-c(eval(YAxisVars),eval(XAxisVar), eval(FirstCatFactor), eval(SecondCatFactor), "catfact")
		}
		if (dim(statdata2)[2]==6 )
		{
			nams<-c(eval(YAxisVars),eval(XAxisVar), eval(FirstCatFactor), eval(SecondCatFactor), "catfact",eval(CaseIDFactor))
		}
		
		colnames(statdata2)<-nams
		k<-dim(statdata2)[1]+1

		for (i in 1 : length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			for (j in 1 : length(unique(levels(as.factor(eval(parse(text = paste("statdata$", FirstCatFactor))))))))
			{
				for (l in 1 : length(unique(levels(as.factor(eval(parse(text = paste("statdata$", SecondCatFactor))))))))
				{
					statdata2[k,2] = levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar)))))[i]
					statdata2[k,3] = levels(as.factor(eval(parse(text = paste("statdata$", FirstCatFactor)))))[j]
					statdata2[k,4] = levels(as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))))[l]
#					statdata2[k,5] = levels(as.factor(statdata$catfact))[j]
# Edit 27th May 2010 (SE's not right)
					statdata2[k,5] = paste(levels(as.factor(eval(parse(text = paste("statdata$", FirstCatFactor)))))[j],levels(as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))))[l])
					k=k+1
				}
			} 
		}
	}

	if(DisplayLegend=="Y")
	{
		if (SEMPlotType =="ColumnPlot")
		{
			if (maxmean >0 && minmean >=0)
			{
				par(las=1) 
				xaxis<-length(unique(eval(parse(text = paste("statdata$", XAxisVar)))))*(length(unique(as.factor(statdata$catfact)))+1)+1+(length(unique(as.factor(statdata$catfact))))/3
				suppressWarnings(bargraph.CI(x.factor = eval(parse(text = paste("statdata2$", XAxisVar))),eval(parse(text = paste("statdata2$", YAxisVars))), group=statdata2$catfact, legend=TRUE, ncol=1, x.leg= "topright", y.leg= 1*yaxis, ylim=c(0,yaxis), main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05, lc=FALSE, xlim=c(0, xaxis)))
				axis(side=1, labels=FALSE, pos=0, tck=0)
				axis(side=2, labels=TRUE, pos=0)
			} else if (maxmean <=0 && minmean <0)
			{
				par(las=1) 
				xaxis<-length(unique(eval(parse(text = paste("statdata$", XAxisVar)))))*(length(unique(as.factor(statdata$catfact)))+1)+1+(length(unique(as.factor(statdata$catfact))))/3
				suppressWarnings(bargraph.CI(eval(parse(text = paste("statdata2$", XAxisVar))),eval(parse(text = paste("statdata2$", YAxisVars))), group=statdata2$catfact, legend=TRUE, ncol=1, x.leg= "bottomright", y.leg= 0*yaxis, ylim=c(yaxis2,0), main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05, uc=FALSE, xlim=c(0, xaxis)))
				axis(side=1, labels=FALSE, pos=0, tck=0)
				axis(side=2, labels=TRUE, pos=0)
			} else 
			{
				par(las=1) 
				xaxis<-length(unique(eval(parse(text = paste("statdata$", XAxisVar)))))*(length(unique(as.factor(statdata$catfact)))+1)+1+(length(unique(as.factor(statdata$catfact))))/3
				suppressWarnings(bargraph.CI(eval(parse(text = paste("statdata2$", XAxisVar))),eval(parse(text = paste("statdata2$", YAxisVars))), group=statdata2$catfact, legend=TRUE, ncol=1, x.leg= "bottomright", y.leg= 0*yaxis, ylim=c(yaxis2,yaxis), main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05, uc=TRUE, xlim=c(0, xaxis)))
				axis(side=1, labels=FALSE, pos=0, tck=0)
				axis(side=2, labels=TRUE, pos=0)
			}
		} else 
		{
			par(las=1) 
			suppressWarnings(lineplot.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))), group=as.factor(statdata$catfact), legend=TRUE, ncol=1, main=MainTitle, xlab=XAxisTitle,  ylab = YAxisTitle, cex=2, err.width=0.05,err.lty=lines, lty=lines, axes=TRUE))
			box(col='white')
			ymin<-min(eval(parse(text = paste("statdata$", YAxisVars))))
			ymax<-max(eval(parse(text = paste("statdata$", YAxisVars))))
			xa<-(c(0:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) )))))
			axis(side=1, labels=FALSE, at = xa)
			axis(side=2, labels=FALSE,at = c(ymin,ymax))
		}
	} else 
	{
		if (SEMPlotType =="ColumnPlot")
		{
			if (maxmean >0 && minmean >=0)
			{
				yaxis3<-maxresp
				xaxis<-length(unique(eval(parse(text = paste("statdata$", XAxisVar)))))*(length(unique(as.factor(statdata$catfact)))+1)+1+(length(unique(as.factor(statdata$catfact))))/3
				par(las=1) 
				bargraph.CI(eval(parse(text = paste("statdata2$", XAxisVar))),eval(parse(text = paste("statdata2$", YAxisVars))), group=statdata2$catfact, legend=FALSE, ncol=1, x.leg= "topright", y.leg= 1*yaxis, ylim=c(0,yaxis3), main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05, lc=FALSE, xlim=c(0, xaxis))
				axis(side=1, labels=FALSE, pos=0, tck=0)
				axis(side=2, labels=TRUE, pos=0)
			} else if (maxmean <=0 && minmean <0)
			{
				yaxis4<-maxresp2
				xaxis<-length(unique(eval(parse(text = paste("statdata$", XAxisVar)))))*(length(unique(as.factor(statdata$catfact)))+1)+1+(length(unique(as.factor(statdata$catfact))))/3
				par(las=1) 
				bargraph.CI(eval(parse(text = paste("statdata2$", XAxisVar))),eval(parse(text = paste("statdata2$", YAxisVars))), group=statdata2$catfact, legend=FALSE, ncol=1, x.leg= "bottomright", y.leg= 0*yaxis, main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05, uc=FALSE, xlim=c(0, xaxis),  ylim=c(yaxis4,0))
				axis(side=1, labels=FALSE, pos=0, tck=0)
				axis(side=2, labels=TRUE, pos=0)
			} else
			{
				
				yaxis3<-maxresp
				yaxis4<-maxresp2
				xaxis<-length(unique(eval(parse(text = paste("statdata$", XAxisVar)))))*(length(unique(as.factor(statdata$catfact)))+1)+1+(length(unique(as.factor(statdata$catfact))))/3
				par(las=1) 
				bargraph.CI(eval(parse(text = paste("statdata2$", XAxisVar))),eval(parse(text = paste("statdata2$", YAxisVars))), group=statdata2$catfact, legend=FALSE, ncol=1, x.leg= "bottomright", y.leg= 0*yaxis, main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, axes=FALSE, cex=0.6, bty=1, err.width=0.05, uc=TRUE, xlim=c(0, xaxis),  ylim=c(yaxis4,yaxis3))
				axis(side=1, labels=FALSE, pos=0, tck=0)
				axis(side=2, labels=TRUE, pos=0)
			}

		} else 
		{
			par(las=1) 
			lineplot.CI(eval(parse(text = paste("statdata$", XAxisVar))),eval(parse(text = paste("statdata$", YAxisVars))), group=as.factor(statdata$catfact), legend=FALSE, ncol=1, main=MainTitle, xlab=XAxisTitle,  ylab = YAxisTitle, cex=2, err.width=0.05,err.lty=lines, lty=lines, axes=TRUE)
			box(col='white')
			ymin<-min(eval(parse(text = paste("statdata$", YAxisVars))))
			ymax<-max(eval(parse(text = paste("statdata$", YAxisVars))))
			xa<-(c(0:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) )))))
			axis(side=1, labels=FALSE, at = xa)
			axis(side=2, labels=FALSE, at = c(ymin,ymax))
		}
	}

	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncSEMPlot), Align="centre")
}

# TWO CAT - seperate,  categorial x (all combinations of factors present)

if(SEMPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
		HTML.title("<bf> ", HR=2, align="left")
		add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
		

		HTML.title(add, HR=0, align="left")
}
if(SEMPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	together<-length(unique(levels(as.factor(statdata$catfact))))
	first<-length(unique(levels(as.factor(eval(parse(text = paste("statdata$", FirstCatFactor)))))))
	second<-length(unique(levels(as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))))))

	if (together==first*second)
	{
		selev<-c(0)
		semean<-c(0)
		semean2<-c(0)
		avemean<-c(0)

		k<-1
		for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			tempdata2<-subset(statdata,as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) == unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i])
			for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))
			{
				tempdata3<-subset(tempdata2,as.factor(tempdata2$catfact) == unique(levels(as.factor(tempdata2$catfact)))[j])
	
				if(dim(tempdata3)[1]==0)
				{
					selev[k]=NA
					semean[k]<-NA
					semean2[k]<-NA
					avemean[k]<-0
				} else 
				{
					if (length(unique(eval(parse(text = paste("tempdata3$", YAxisVars)))))==1)
					{
						selev[k]=0
						semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
						semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
						avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					} else 
					{
						selev[k]=se(eval(parse(text = paste("tempdata3$", YAxisVars))), na.rm=TRUE)
						semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))+selev[k]
						semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))-selev[k]
						avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					}
				}
				k=k+1
			}
		}

		#Calculating the yaxis max value
		maxresp<-max(semean, na.rm=TRUE)
		minresp<-0
		rangeresp<-maxresp-minresp
		yaxis<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact))))*0.05

		maxresp2<-min(semean2, na.rm=TRUE)
		minresp<-0
		rangeresp2<- maxresp2
		yaxis2<-maxresp2 + rangeresp2*length(unique(levels(as.factor(statdata$catfact))))*0.05

		#creating the new dataset
		a<-1
		b<-1
		c<-1
		t<-1
		yax<-c(0)
		xax<-c(0)
		fcat<-(0)
		gcat<-(0)	
		means<-c(0)
		te<-c(0)

		upper<-semean
		lower<-semean2
		maxmean<-max(avemean,na.rm=TRUE)
		minmean<-min(avemean,na.rm=TRUE)


		for (w in 1:51)
		{
			for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
			{
				for (j in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", FirstCatFactor)))   )))))	
				{
					for (k in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", SecondCatFactor)))   )))))	
					{
						yax[a]=te[1]
						xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
						fcat[a]=unique(levels(as.factor(  eval(parse(text = paste("statdata$", FirstCatFactor)))   )))[j]
						gcat[a]=unique(levels(as.factor(  eval(parse(text = paste("statdata$", SecondCatFactor)))   )))[k]		
						a=a+1		
					}
				}
			}
		}

		for (w in 1:50)
		{
			for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
			{
				for (j in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", FirstCatFactor)))   )))))	
				{
					for (k in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", SecondCatFactor)))   )))))	
					{
						yax[a]=avemean[c]
						xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
						fcat[a]=unique(levels(as.factor(  eval(parse(text = paste("statdata$", FirstCatFactor)))  )))[j]
						gcat[a]=unique(levels(as.factor(  eval(parse(text = paste("statdata$", SecondCatFactor)))   )))[k]		
						a=a+1	
						c=c+1	
					}
				}
			}
			c=1
		}
		for (j in 1:(length(unique(levels(as.factor(  statdata$catfact))))*length(unique(levels(as.factor( eval(parse(text = paste("statdata$", XAxisVar)))    )))))	)
		{
			if (avemean[j]>0)
			{
				yax[j+a-1]=upper[j]
			} else
			{
				yax[j+a-1]=lower[j]
			}
		}
		for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			for (j in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", FirstCatFactor)))   )))))	
			{
				for (k in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", SecondCatFactor)))   )))))	
				{
					xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
					fcat[a]=unique(levels(as.factor(  eval(parse(text = paste("statdata$", FirstCatFactor)))   )))[j]	
					gcat[a]=unique(levels(as.factor(  eval(parse(text = paste("statdata$", SecondCatFactor)))   )))[k]	
					a=a+1
					b=b+1		
				}
			}
		}

		yax2<-as.numeric(yax)
		tempdata3<-data.frame(yax2,xax,fcat,gcat)
		#Plot
		ncSEMPlot <- sub(".html", "ncSEMPlot.jpg", htmlFile)
		jpeg(ncSEMPlot)
		if (SEMPlotType =="ColumnPlot")
		{
			if (maxmean >0 && minmean >=0)
			{
				par(las=1) 
				suppressWarnings(bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat)*as.factor(tempdata3$gcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(te[1],yaxis),))
			} else if (maxmean <=0 && minmean <0)
			{
				par(las=1) 
				suppressWarnings(bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat)*as.factor(tempdata3$gcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(yaxis2,0)))
			} else if (maxmean >0 && minmean <0)
			{
				par(las=1) 
				suppressWarnings(p<-bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat)*as.factor(tempdata3$gcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(yaxis2,yaxis),))
				update(p, panel=function(...)
				{
			   	panel.bwplot(...)
   				panel.abline(h=0, col="black", lty=1, lwd=1)
				})
			} 
		} else 
		{
			HTML.title("<bf> ", HR=2, align="left")
			HTML.title("<bf> The separate option is not currently available for the SEM line plot. Use the overlaid option instead.", HR=0, align="left")
		}
	} else 
	{
		selev<-c(0)
		semean<-c(0)
		semean2<-c(0)
		avemean<-c(0)
	
		k<-1
		for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
		{
			tempdata2<-subset(statdata,as.factor(eval(parse(text = paste("statdata$", XAxisVar)))) == unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i])
			for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))
			{
				tempdata3<-subset(tempdata2,as.factor(tempdata2$catfact) == unique(levels(as.factor(tempdata2$catfact)))[j])
	
				if(dim(tempdata3)[1]==0)
				{
					selev[k]=NA
					semean[k]<-NA
					semean2[k]<-NA
					avemean[k]<-0
				} else 
				{
					if (length(unique(eval(parse(text = paste("tempdata3$", YAxisVars)))))==1)
					{
						selev[k]=0
						semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
						semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
						avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					} else 
					{
					selev[k]=se(eval(parse(text = paste("tempdata3$", YAxisVars))), na.rm=TRUE)
					semean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))+selev[k]
					semean2[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))-selev[k]
					avemean[k]=mean(eval(parse(text = paste("tempdata3$", YAxisVars))))
					}
				}
				k=k+1
			}
		}
	
		#Calculating the yaxis max value
		maxresp<-max(semean, na.rm=TRUE)
		minresp<-0
		rangeresp<-maxresp-minresp
		yaxis<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact))))*0.05
	
		maxresp2<-min(semean2, na.rm=TRUE)
		minresp<-0
		rangeresp2<- maxresp2
		yaxis2<-maxresp2 + rangeresp2*length(unique(levels(as.factor(statdata$catfact))))*0.05
	
		#creating the new dataset
		a<-1
		b<-1
		c<-1
		t<-1
		yax<-c(0)
		xax<-c(0)
		fcat<-(0)	
		means<-c(0)
		te<-c(0)
		upper<-semean
		lower<-semean2
		maxmean<-max(avemean,na.rm=TRUE)
		minmean<-min(avemean,na.rm=TRUE)

		for (w in 1:51)
		{
			for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
			{
				for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))	
				{
					yax[a]=te[1]
					xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
					fcat[a]=unique(levels(as.factor(  statdata$catfact   )))[j]		
					a=a+1		
				}
			}
		}
		for (w in 1:50)
		{
			for (i in 1:length(unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))))
			{
				for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))	
				{
					yax[a]=avemean[c]
					xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
					fcat[a]=unique(levels(as.factor(  statdata$catfact   )))[j]		
					a=a+1	
					c=c+1	
				}
			}
			c=1
		}
		for (j in 1:(length(unique(levels(as.factor(  statdata$catfact))))*length(unique(levels(as.factor( eval(parse(text = paste("statdata$", XAxisVar)))    )))))	)
		{
			if (avemean[j]>0)
			{
				yax[j+a-1]=upper[j]
			} else
			{
				yax[j+a-1]=lower[j]
			}
		}
		for (i in 1:length(unique(levels(as.factor(  eval(parse(text = paste("statdata$", XAxisVar)))   )))))	
		{
			for (j in 1:length(unique(levels(as.factor(  statdata$catfact   )))))	
			{
				xax[a]=unique(levels(as.factor(eval(parse(text = paste("statdata$", XAxisVar))))))[i]
				fcat[a]=unique(levels(as.factor(  statdata$catfact   )))[j]		
				a=a+1
				b=b+1		
			}
		}
		yax2<-as.numeric(yax)
		tempdata3<-data.frame(yax2,xax,fcat)
	
		#Plot
		ncSEMPlot <- sub(".html", "ncSEMPlot.jpg", htmlFile)
		jpeg(ncSEMPlot)
		if (SEMPlotType =="ColumnPlot")
		{
			if (maxmean >0 && minmean >=0)
			{
				par(las=1) 
				suppressWarnings(bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(te[1],yaxis),))
			} else if (maxmean <=0 && minmean <0)
			{
				par(las=1) 
				suppressWarnings(bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(yaxis2,0)))
			} else if (maxmean >0 && minmean <0)
			{
				par(las=1) 
				suppressWarnings(p<-bwplot(tempdata3$yax2~as.factor(tempdata3$xax)|as.factor(tempdata3$fcat), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black"),  plot.symbol = list(col="white")), coef=0, fill="grey", col=NA, ylim=c(yaxis2,yaxis)))
				update(p, panel=function(...)
				{
			   	panel.bwplot(...)
	    			panel.abline(h=0, col="black", lty=1, lwd=1)
				})
			} 
		} else 
		{
			HTML.title("<bf> ", HR=2, align="left")
			HTML.title("<bf> The separate option is not currently available for the SEM line plot. Use the overlaid option instead.", HR=0, align="left")
		}
	}
}

if(SEMPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && SEMPlotType =="ColumnPlot" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncSEMPlot), Align="centre")
}

#Boxplot - y should be numerical, x should be categorical

#Titles
if(BoxPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"&& YAxisVars != "NULL")
{
	add<-c("Boxplot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
} else if(BoxPlot == "Y" && (FirstCatFactor != "NULL" || SecondCatFactor != "NULL")&& YAxisVars != "NULL")
{
	add<-c("Categorised boxplot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
}

#NON CATegorised Scatterplot - categorical x
if(BoxPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(BoxPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#Plot
	ncboxplot <- sub(".html", "ncboxplot.jpg", htmlFile)
	jpeg(ncboxplot)

	if (Outliers=="N")
	{
		par(las=1) 
		bw<-	boxplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar))), col="black", range = 1.5, outline=FALSE)
		bxp(bw,boxfill= "grey95", whisklty=1,medpch=16, medlty="blank", outline=FALSE, main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle)
	} else {
		par(las=1) 
		bw<-	boxplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar))), col="black", range = 1.5, outline=TRUE)
		bxp(bw,boxfill= "grey95", whisklty=1, medpch=16, medlty="blank", main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle)
	}
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncboxplot), Align="centre")
}	

# ONE CAT - seperate,  categorial x

if(BoxPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
		HTML.title("<bf> ", HR=2, align="left")
		add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
		

		HTML.title(add, HR=0, align="left")
}
if(BoxPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#Plot
	ncboxplot <- sub(".html", "ncboxplot.jpg", htmlFile)
	jpeg(ncboxplot)

	if (Outliers=="N")
	{
		par(las=1) 
		bwplot(eval(parse(text = paste("statdata$", YAxisVars)))~as.factor(eval(parse(text = paste("statdata$", XAxisVar))))|as.factor(statdata$catfact), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black", pch=20, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black", fill="grey95"),  plot.symbol = list(col="white")))
	} else {
		par(las=1) 
		bwplot(eval(parse(text = paste("statdata$", YAxisVars)))~as.factor(eval(parse(text = paste("statdata$", XAxisVar))))|as.factor(statdata$catfact), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black", pch=20, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black", fill="grey95"),  plot.symbol = list(col="black")))
	}
}
if(BoxPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL"))  && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void2<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncboxplot), Align="centre")
}

# ONE CAT - overlaid,  categorial x
if(BoxPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
		HTML.title("<bf> ", HR=2, align="left")
		add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
		

		HTML.title(add, HR=0, align="left")
}
if(BoxPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#Plot
	ncboxplot <- sub(".html", "ncboxplot.jpg", htmlFile)
	jpeg(ncboxplot)
	if (Outliers=="N")
	{
		par(las=1) 
		bw<-	boxplot(eval(parse(text = paste("statdata$", YAxisVars)))~as.factor(eval(parse(text = paste("statdata$", XAxisVar))))*as.factor(statdata$catfact), main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle, col="black", range = 1.5, outline=FALSE)
		bxp(bw,boxfill= "grey95", whisklty=1,medpch=16, medlty="blank", outline=FALSE,main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle)
	} else {
		par(las=1) 
		bw<-	boxplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))*as.factor(statdata$catfact), main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle, col="black", range = 1.5, outline=TRUE)
		bxp(bw,boxfill= "grey95", whisklty=1,medpch=16, medlty="blank",main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle)
	}
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncboxplot), Align="centre")
}

# TWO CAT - seperate categorical y
if(BoxPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL"  && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(BoxPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL"  && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	#Plot
	ncboxplot <- sub(".html", "ncboxplot.jpg", htmlFile)
	jpeg(ncboxplot)

	if (Outliers=="N")
	{
		par(las=1) 
		bwplot(eval(parse(text = paste("statdata$", YAxisVars)))~as.factor(eval(parse(text = paste("statdata$", XAxisVar))))|as.factor(eval(parse(text = paste("statdata$", FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black", pch=20, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black", fill="grey95"),  plot.symbol = list(col="white")))
	} else {
		par(las=1) 
		bwplot(eval(parse(text = paste("statdata$", YAxisVars)))~as.factor(eval(parse(text = paste("statdata$", XAxisVar))))|as.factor(eval(parse(text = paste("statdata$", FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black", pch=20, strip = strip.custom(style=1, bg="grey95"), par.settings = list(box.umbrella = list(lty = 1, col="black"),box.rectangle = list(col="black", fill="grey95"),  plot.symbol = list(col="black")))
	}
}
if(BoxPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL"  && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncboxplot), Align="centre")
}

if(BoxPlot == "Y" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	HTMLbr()
	title<-c("Description")
	HTML.title(title, HR=2, align="left")
	HTML.title("Median is denoted by a circle within the box.", HR=0, align="left")
	HTML.title("Box indicates the interquartile range.", HR=0, align="left")
	HTML.title("Outlier range (1.5 X interquartile range) is denoted by the whiskers.", HR=0, align="left")
	if (Outliers=="Y")
	{
		HTML.title("Individual observations that lie outside the outlier range are included on the plot using o's.", HR=0, align="left")
	}
}

#Scatterplot#

#Titles
if(ScatterPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"&& YAxisVars != "NULL")
{
	add<-c("Scatterplot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
} else if(ScatterPlot == "Y" && (FirstCatFactor != "NULL" || SecondCatFactor != "NULL")&& YAxisVars != "NULL")
{
	add<-c("Categorised scatterplot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
}

#Calculating correlation coefficients for categorised scatterplots
if(CorrelationPValue == "Y" && (FirstCatFactor != "NULL" || SecondCatFactor != "NULL") && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE")
{	rows<-dim(statdata)[1]
	cols<-dim(statdata)[2]
	nlevels<-length(unique(as.factor(statdata$catfact)))

	extra<-matrix(data=NA, nrow=rows, ncol=nlevels)
	for (i in 1:nlevels)
	{
		for (j in 1:rows)
		{
			if (as.factor(statdata$catfact)[j] == unique(as.factor(statdata$catfact))[i])
			{
				extra[j,i]<-eval(parse(text = paste("statdata$", YAxisVars)))[j]
			}
		}
	}

	newdata<-cbind(statdata, extra)
	catplotdata<-data.frame(newdata)
	tempdata<-catplotdata
	catleg<-matrix(nrow=length(unique(levels(as.factor(tempdata$catfact)))),ncol=1)
	ptab<-c(0)
	rhotab<-c(0)
	for (k in 1:nlevels)
	{
		tmpdata<-catplotdata
		tmpdata2<-subset(tmpdata, tmpdata$catfact == unique(levels(as.factor(tmpdata$catfact)))[k])
		correlation<-cor.test(eval(parse(text = paste("tmpdata2$",YAxisVars))),eval(parse(text = paste("tmpdata2$",XAxisVar))), method="pearson")
		pcorr<-correlation$p.value
		rho<-correlation$estimate
		pcorr2<-format(round(pcorr, 3), nsmall=3, scientific=FALSE)
		rho<-format(round(rho, 2), nsmall=2, scientific=FALSE)
		if (pcorr2<0.001) 
		{
			pcorr2<-0.001
			pcorr2<- paste("<",pcorr2)
		}
		
		ptab[k]<-pcorr2
		rhotab[k]<-rho
	}
	
	temp<-cbind( rhotab, " ", ptab)
	header<-c(" "," "," ")
	corrtab<-rbind(header, temp)
	temp6<-c("Correlation coefficient", " ","p-value")
	colnames(corrtab)<-temp6
	
	if (FirstCatFactor != "NULL" && SecondCatFactor != "NULL")
	{
		good3<-c("Categorisation factor level combinations")
	} else {
		good3<-c("Categorisation Factor levels")
	}
	for(i in 1:(dim(corrtab)[1]-1)){good3[i+1]<-levels(as.factor(tmpdata$catfact))[i]}

	row.names(corrtab)<-good3
}

# NON CATegorised Scatterplot - continuous
if(ScatterPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL" && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE" )
{
	#Plot
	ncscatterplot <- sub(".html", "ncscatterplot.jpg", htmlFile)
	jpeg(ncscatterplot)
	par(las=1) 
	plot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar))), main=MainTitle,xlab=XAxisTitle, 	ylab = YAxisTitle, col="black")

	#Best fit line
	if(LinearFit == "Y")
	{
		abline(lm(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))))
	}

	#Corrleation and p
	if(CorrelationPValue == "Y")
	{
		correlation<-cor.test(eval(parse(text = paste("statdata$", YAxisVars))),eval(parse(text = paste("statdata$", XAxisVar))), 	method="pearson")
		pcorr<-correlation$p.value
		rho<-correlation$estimate
		pcorr2<-format(round(pcorr, 3), nsmall=3, scientific=FALSE)
		rho<-format(round(rho, 2), nsmall=2, scientific=FALSE)
		if (pcorr2<0.001) 
		{
			pcorr2<-0.001
			pcorr2<- paste("<",pcorr2)
		}
		corrleg1<-c("Pearson's correlation coef: ")
		corrleg1<-paste(corrleg1, rho, sep="")
		corrleg1<-paste(corrleg1," associated p-value: ", sep="")
		corrleg1<-paste(corrleg1, pcorr2, sep="")
		title(sub=corrleg1)
	}
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncscatterplot), Align="centre")
}

#NON CATegorised Scatterplot - categorical 
if(ScatterPlot == "Y" && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE") && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"  )
{

	#Plot
	ncscatterplot2 <- sub(".html", "ncscatterplot2.jpg", htmlFile)
	jpeg(ncscatterplot2)
	par(las=1) 
	xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar))), main=MainTitle, xlab=XAxisTitle, 	ylab = YAxisTitle, col="black")
}

if(ScatterPlot == "Y" && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE") && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"  )
{

	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncscatterplot2), Align="centre")
}

# ONE CAT - overlaid, continuous 
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL") || (FirstCatFactor != "NULL" && SecondCatFactor != "NULL")) && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE" && GraphStyle == "Overlaid")
{
    #Plot
    rows<-dim(statdata)[1]
    cols<-dim(statdata)[2]
    nlevels<-length(unique(as.factor(statdata$catfact)))
    extra<-matrix(data=NA, nrow=rows, ncol=nlevels)
    for (i in 1:nlevels)
    {
        for (j in 1:rows)
        {
            if (as.factor(statdata$catfact)[j] == unique(as.factor(statdata$catfact))[i])
            {
                extra[j,i]<-eval(parse(text = paste("statdata$", YAxisVars)))[j]
            }
        }
    }

    newdata<-cbind(statdata, extra)
    catplotdata<-data.frame(newdata)
    
    for (k in 1:nlevels)
    {
        tempdata<-catplotdata
        tempdata2<-subset(tempdata, statdata$catfact == unique(levels(as.factor(tempdata$catfact)))[k])
    }

    index<-c(1:nlevels)
    newnames<-c(colnames(statdata),index)
    colnames(catplotdata)<-newnames
    ncscatterplot3 <- sub(".html", "ncscatterplot3.jpg", htmlFile)
    jpeg(ncscatterplot3)

    #Adjusting y  axis to fit in legend
    maxresp<-max(eval(parse(text = paste("statdata$",YAxisVars))))
    minresp<-min(eval(parse(text = paste("statdata$",YAxisVars))))
    rangeresp<-maxresp-minresp
    maxob<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact))))*0.075
    minob<-minresp - rangeresp*0.1

    cat<-c(as.factor(statdata$catfact))
    if(DisplayLegend=="Y")
    {
		par(las=1) 
        plot(eval(parse(text = paste("statdata$",YAxisVars)))~eval(parse(text = paste("statdata$",XAxisVar))), data=catplotdata, col=cat,pch=cat, main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, ylim=c(minob,maxob))
        legend("topright", legend=levels(as.factor(tempdata$catfact)),cex=0.6,pch=c(1:nlevels), lty=1:nlevels,bg="white", col=c(1:nlevels))
    } else 
    {
	par(las=1) 
        plot(eval(parse(text = paste("statdata$",YAxisVars)))~eval(parse(text = paste("statdata$",XAxisVar))), data=catplotdata, col=cat,pch=cat, main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle)#, ylim=c(minob,maxob))
       
    }

	#Best fit line 
	if(LinearFit == "Y")
	{
		for (k in 1:nlevels)
		{
			tempdata<-catplotdata
			tempdata2<-subset(tempdata, tempdata$catfact == unique(levels(as.factor(tempdata$catfact)))[k])
			abline(lm(eval(parse(text = paste("tempdata2$",YAxisVars)))~eval(parse(text = paste("tempdata2$",XAxisVar)))), col=k)
		}
	}
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncscatterplot3), Align="centre")

	#Corrleation and p
	if(CorrelationPValue == "Y")
	{
		HTMLbr()
		title<-c("Pearson's correlation coefficients and p-values")
		HTML.title(title, HR=2, align="left")
		HTML(corrtab, , align="left" , classfirstline="second")
	}
}

# ONE CAT - seperate, continuous
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE"  && GraphStyle == "Separate")
{
	#Plot
	ncscatterplot2 <- sub(".html", "ncscatterplot2.jpg", htmlFile)
	jpeg(ncscatterplot2)

	if(LinearFit == "Y")
	{
		par(las=1)
		xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))|as.factor(statdata$catfact), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black",strip = strip.custom(style=1, bg="grey95"), type = c("g", "p", "r"))
	} else {
		par(las=1)
		xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))|as.factor(statdata$catfact), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black",strip = strip.custom(style=1, bg="grey95"))
	}
}
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE"  && GraphStyle == "Separate")
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncscatterplot2), Align="centre")

	#Corrleation and p 
	if(CorrelationPValue == "Y")
	{
		HTMLbr()
		title<-c("Pearson's correlation coefficients and p-values")
		HTML.title(title, HR=2, align="left")
		HTML(corrtab, classfirstline="second", align="left")
	}
}

# ONE CAT - overlaid, categorial
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor != "NULL" && SecondCatFactor != "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE" ) && GraphStyle == "Overlaid")
{
	#Plot
	rows<-dim(statdata)[1]
	cols<-dim(statdata)[2]
	nlevels<-length(unique(as.factor(statdata$catfact)))
	extra<-matrix(data=NA, nrow=rows, ncol=nlevels)
	for (i in 1:nlevels)
	{
		for (j in 1:rows)
		{
			if (statdata$catfact[j] == unique(as.factor(statdata$catfact))[i])
			{
				extra[j,i]<-eval(parse(text = paste("statdata$", YAxisVars)))[j]
			}
		}
	}
	newdata<-cbind(statdata, extra)
	catplotdata<-data.frame(newdata)
	for (k in 1:nlevels)
	{
		tempdata<-catplotdata
		tempdata2<-subset(tempdata, tempdata$catfact == unique(levels(as.factor(tempdata$catfact)))[k])
	}
	index<-c(1:nlevels)
	newnames<-c(colnames(statdata),index)
	colnames(catplotdata)<-newnames
	ncscatterplot3 <- sub(".html", "ncscatterplot3.jpg", htmlFile)
	jpeg(ncscatterplot3)

	if (is.numeric(eval(parse(text = paste("statdata$",YAxisVars))))==TRUE)
	{
		#Adjusting y  axis to fit in legend
		maxresp<-max(eval(parse(text = paste("statdata$",YAxisVars))))
		minresp<-min(eval(parse(text = paste("statdata$",YAxisVars))))
		rangeresp<-maxresp-minresp
		maxob<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact))))*0.075
		minob<-minresp - rangeresp*0.1

		cat<-c(as.factor(statdata$catfact))			
		catlab<-c(levels(eval(parse(text = paste("statdata$",XAxisVar)))))

		if(DisplayLegend=="Y")
		{
			par(las=1) 
			plot(as.numeric(eval(parse(text = paste("statdata$",YAxisVars))))~as.numeric(eval(parse(text = paste("statdata$",XAxisVar)))), type = "p", data=catplotdata, 	col=cat,pch=cat, main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, xaxt="n",ylim=c(minob,maxob))
			axis(at=1:length(unique(levels(eval(parse(text = paste("statdata$",XAxisVar)))))), labels = catlab,side=1)
			axis(side=2)
			legend("topright", legend=levels(as.factor(tempdata$catfact)),cex=0.6,pch=c(1:nlevels), bg="white", col=c(1:nlevels))
		} else {
			par(las=1) 
			plot(as.numeric(eval(parse(text = paste("statdata$",YAxisVars))))~as.numeric(eval(parse(text = paste("statdata$",XAxisVar)))), type = "p", data=catplotdata, 	col=cat,pch=cat, main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, xaxt="n")
			axis(at=1:length(unique(levels(eval(parse(text = paste("statdata$",XAxisVar)))))), labels = catlab,side=1)
			axis(side=2)
		}
	} else  if (is.numeric(eval(parse(text = paste("statdata$",YAxisVars))))==FALSE)
	{
		#Adjusting y  axis to fit in legend
		maxresp<-max(as.numeric(eval(parse(text = paste("statdata$",YAxisVars)))))
		minresp<-min(as.numeric(eval(parse(text = paste("statdata$",YAxisVars)))))
		rangeresp<-maxresp-minresp
		maxob<-maxresp + rangeresp*length(unique(levels(as.factor(statdata$catfact))))*0.075
		minob<-minresp - rangeresp*0.1

		cat<-c(as.factor(statdata$catfact))
		catlab<-c(levels(eval(parse(text = paste("statdata$",YAxisVars)))))

		if(DisplayLegend=="Y")
		{
			par(las=1)
			plot(as.numeric(eval(parse(text = paste("statdata$",YAxisVars))))~as.numeric(eval(parse(text = paste("statdata$",XAxisVar)))), type = "p", data=catplotdata, 	col=cat,pch=cat, main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, yaxt="n", ylim=c(minob,maxob))
			axis(at=1:length(unique(levels(eval(parse(text = paste("statdata$",YAxisVars)))))), labels = catlab, side=2, par(las=1))
			axis(side=1)
			legend("topright", legend=levels(as.factor(tempdata$catfact)),cex=0.6,pch=c(1:nlevels), bg="white", col=c(1:nlevels))
		} else {
			par(las=1)
			plot(as.numeric(eval(parse(text = paste("statdata$",YAxisVars))))~as.numeric(eval(parse(text = paste("statdata$",XAxisVar)))), type = "p", data=catplotdata, 	col=cat,pch=cat, main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, yaxt="n")
			axis(at=1:length(unique(levels(eval(parse(text = paste("statdata$",YAxisVars)))))), labels = catlab, side=2, par(las=1))
			axis(side=1)
		}
	}
}
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor != "NULL" && SecondCatFactor != "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE" ) && GraphStyle == "Overlaid")
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncscatterplot3), Align="centre")
}

# ONE CAT - seperate,  categorial
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE" ) && GraphStyle == "Separate")
{
	#Plot
	ncscatterplot2 <- sub(".html", "ncscatterplot2.jpg", htmlFile)
	jpeg(ncscatterplot2)
	par(las=1)
	xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))|as.factor(statdata$catfact), main=MainTitle, 	xlab=XAxisTitle, ylab = YAxisTitle, col="black", strip = strip.custom(style=1, bg="grey95"))
}
if(ScatterPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE" ) && GraphStyle == "Separate")
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", ncscatterplot2), Align="centre")
}

# TWO CAT - seperate continuous
if(ScatterPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE"  && GraphStyle == "Separate")
{
	#Plot
	scatterPlot <- sub(".html", "scatterPlot.jpg", htmlFile)
	jpeg(scatterPlot)

	#Best fit line comment
	if(LinearFit == "Y")
	{
		par(las=1)
		xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))|as.factor(eval(parse(text = paste("statdata$",FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))), main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, col="black",strip = strip.custom(style=1, bg="grey95"), type = c("g", "p", "r"))
	} else {
		par(las=1)
		xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))|as.factor(eval(parse(text = paste("statdata$",FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))), main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, col="black",strip = strip.custom(style=1, bg="grey95"))
	}
}
if(ScatterPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="TRUE" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="TRUE"  && GraphStyle == "Separate")
{
	void <- HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", scatterPlot), Align="centre")

	if(CorrelationPValue == "Y")
	{
		HTMLbr()
		title<-c("Pearson's correlation coefficients and p-values")
		HTML.title(title, HR=2, align="left")
		HTML(corrtab, classfirstline="second", align="left")
	}
}

# TWO CAT - overlaid continuous
#covered by above code

# TWO CAT - seperate categorical
if(ScatterPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE")  && GraphStyle == "Separate")
{
	#Plot
	scatterPlot <- sub(".html", "scatterPlot.jpg", htmlFile)
	jpeg(scatterPlot)
	par(las=1)
	xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar)))|as.factor(eval(parse(text = paste("statdata$",FirstCatFactor))))*as.factor(eval(parse(text = paste("statdata$", SecondCatFactor)))), main=MainTitle, xlab=XAxisTitle, ylab = YAxisTitle, col="black",strip = strip.custom(style=1, bg="grey95"))
}

if(ScatterPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && (is.numeric(eval(parse(text = paste("statdata$", XAxisVar))))=="FALSE" || is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))=="FALSE")  && GraphStyle == "Separate")
{
	void <- HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", scatterPlot), Align="centre")
}

#Case profiles plot - y should be numerical
#Titles
if(CaseProfilesPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"&& YAxisVars != "NULL")
{
	add<-c("Case profiles plot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
} else if(CaseProfilesPlot  == "Y" && (FirstCatFactor != "NULL" || SecondCatFactor != "NULL")&& YAxisVars != "NULL")
{
	add<-c("Categorised case profiles plot")
	HTMLbr()
	HTML.title(add, HR=2, align="left")
}

#NON CATegorised CaseProfilesPlot
if(CaseProfilesPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	HTML.title(add, HR=0, align="left")
}
if(CaseProfilesPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"   && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	with(statdata, statdata[order(eval(parse(text = paste("statdata$", CaseIDFactor))), eval(parse(text = paste("statdata$", XAxisVar)))), ])
	#Plot
	nccaseplot <- sub(".html", "nccaseplot.jpg", htmlFile)
	jpeg(nccaseplot)
	par(las=1)
	p<-xyplot(eval(parse(text = paste("statdata$", YAxisVars)))~eval(parse(text = paste("statdata$", XAxisVar))), groups=eval(parse(text = paste("statdata$", CaseIDFactor))), type="o", data=statdata, main=MainTitle,xlab=CPXAxisTitle, ylab = YAxisTitle )
	if (ReferenceLine!="NULL")
	{
		update(p, panel=function(...)
		{
    		panel.xyplot(...)
    		panel.abline(h=ReferenceLine, col="black", lty=2, lwd=2)
		})
	} else {
		update(p, panel=function(...)
		{
    		panel.xyplot(...)
		})
	}
}
if(CaseProfilesPlot == "Y" && FirstCatFactor == "NULL" && SecondCatFactor == "NULL"  && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE )
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nccaseplot), Align="centre")
}

# ONE CAT - seperate,  categorial x
if(CaseProfilesPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
		HTML.title("<bf> ", HR=2, align="left")
		add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
		HTML.title(add, HR=0, align="left")
}
if(CaseProfilesPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	dd<-data.frame(with(statdata, statdata[order(as.factor(statdata$catfact), eval(parse(text = paste("statdata$", CaseIDFactor))), eval(parse(text = paste("statdata$", XAxisVar)))), ]))
	nrow=dim(dd)[1]
	colours<-c(unique(levels(as.factor(dd$catfact)))[1])
	j=2
	k=1
	for ( i in 1:(nrow-1))
	{
		if (eval(parse(text = paste("dd$", CaseIDFactor)))[i+1]!=eval(parse(text = paste("dd$", CaseIDFactor)))[i] )
		{
			if(dd$catfact[i+1]==dd$catfact[i])
			{
				colours[j]=unique(levels(as.factor(dd$catfact)))[k]
				j=j+1
			} else {
				k=k+1
				colours[j]=unique(levels(as.factor(dd$catfact)))[k]
				j=j+1
			}
		}
	}
	col<-c(1)
	for (i in 1:length(colours))
	{
		for (j in 1:length(unique(levels(as.factor(dd$catfact)))))
		{
			if (colours[i] == unique(levels(as.factor(dd$catfact)))[j])
			{
				col[i]=j
			}
		}
	}
	anim<-c(1)
	j<-1
	for ( i in 1:(nrow-1))
	{
		if (eval(parse(text = paste("dd$", CaseIDFactor)))[i+1]==eval(parse(text = paste("dd$", CaseIDFactor)))[i] )
		{
			anim[i+1]=j
		} else {
			j=j+1
			anim[i+1]=j
		}
	}
	dd2<-data.frame(cbind(dd,anim))
	#Plot
	nccaseplot <- sub(".html", "nccaseplot.jpg", htmlFile)
	jpeg(nccaseplot)
	lev<-c(1:length(unique(levels(as.factor(statdata$catfact)))))
	par(las=1)
	p<-xyplot(eval(parse(text = paste("dd2$", YAxisVars)))~eval(parse(text = paste("dd2$", XAxisVar)))|as.factor(dd2$catfact), groups=dd2$anim, type="o", data=dd, strip=strip.custom(style=1, bg="grey95"), main=MainTitle,xlab=CPXAxisTitle, ylab = YAxisTitle)#, par.settings = list( superpose.line = list(col=lev, lwd = 1) ),auto.key = list(space = "right", text=(unique(levels(as.factor(statdata$catfact)))), points = FALSE, type="b", lines = T,cex=1), col=col) 
	if (ReferenceLine!="NULL")
	{
		update(p, panel=function(...)
			{
        		panel.xyplot(...)
        		panel.abline(h=ReferenceLine, col="black", lty=2, lwd=2)
			})
	} else {
		update(p, panel=function(...)
			{
        		panel.xyplot(...)
        	})
	}
}
if(CaseProfilesPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")) && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nccaseplot), Align="centre")
}

# ONE CAT - overlaid,  categorial x
if(CaseProfilesPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	

	HTML.title(add, HR=0, align="left")
}
if(CaseProfilesPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	dd<-data.frame(with(statdata, statdata[order(as.factor(statdata$catfact), eval(parse(text = paste("statdata$", CaseIDFactor))), eval(parse(text = paste("statdata$", XAxisVar)))), ]))
	nrow=dim(dd)[1]
	colours<-c(unique(levels(as.factor(dd$catfact)))[1])
	j=2
	k=1
	for ( i in 1:(nrow-1))
	{
		if (eval(parse(text = paste("dd$", CaseIDFactor)))[i+1]!=eval(parse(text = paste("dd$", CaseIDFactor)))[i] )
		{
			if(dd$catfact[i+1]==dd$catfact[i])
			{
				colours[j]=unique(levels(as.factor(dd$catfact)))[k]
				j=j+1
			} else {
				k=k+1
				colours[j]=unique(levels(as.factor(dd$catfact)))[k]
				j=j+1
			}
		}
	}
	col<-c(1)
	for (i in 1:length(colours))
	{
		for (j in 1:length(unique(levels(as.factor(dd$catfact)))))
		{
			if (colours[i] == unique(levels(as.factor(dd$catfact)))[j])
			{
				col[i]=j
			}
		}
	}
	anim<-c(1)
	j<-1
	for ( i in 1:(nrow-1))
	{
		if (eval(parse(text = paste("dd$", CaseIDFactor)))[i+1]==eval(parse(text = paste("dd$", CaseIDFactor)))[i] )
		{
			anim[i+1]=j
		} else {
			j=j+1
			anim[i+1]=j
		}
	}
	dd2<-data.frame(cbind(dd,anim))
	lev<-c(1:length(unique(levels(as.factor(statdata$catfact)))))
	#Plot
	nccaseplot <- sub(".html", "nccaseplot.jpg", htmlFile)
	jpeg(nccaseplot)
	if(DisplayLegend=="Y")
	{
		par(las=1)
		p<-xyplot(eval(parse(text = paste("dd2$", YAxisVars)))~eval(parse(text = paste("dd2$", XAxisVar))), groups=dd2$anim, type="o", data=dd, strip=strip.custom(style=1, bg="grey95"), main=MainTitle,xlab=CPXAxisTitle, ylab = YAxisTitle, col = col,par.settings = list( superpose.line = list(col=lev, lwd = 1) ),auto.key = list(space = "right", text=(unique(levels(as.factor(statdata$catfact)))), points = FALSE, type="b", lines = T,cex=1))#, key=list(lines=c(1:3), text=unique(levels(as.factor(statdata$catfact))), points=TRUE , lines = TRUE,space = "right")) 
	} else {
		par(las=1)
		p<-xyplot(eval(parse(text = paste("dd2$", YAxisVars)))~eval(parse(text = paste("dd2$", XAxisVar))), groups=dd2$anim, type="o", data=dd, strip=strip.custom(style=1, bg="grey95"), main=MainTitle,xlab=CPXAxisTitle, ylab = YAxisTitle, col = col,par.settings = list( superpose.line = list(col=lev, lwd = 1) ))#, key=list(lines=c(1:3), text=unique(levels(as.factor(statdata$catfact))), points=TRUE , lines = TRUE,space = "right")) 
	}
	if (ReferenceLine!="NULL")
	{
		update(p, panel=function(...)
		{
    		panel.xyplot(...)
    		panel.abline(h=ReferenceLine, col="black", lty=2, lwd=2)
		})
	} else {
		update(p, panel=function(...)
		{
			panel.xyplot(...)
		})
	}
}
if(CaseProfilesPlot == "Y" && ((FirstCatFactor != "NULL" && SecondCatFactor == "NULL") || (FirstCatFactor == "NULL" && SecondCatFactor != "NULL")|| (FirstCatFactor != "NULL" && SecondCatFactor != "NULL"))   && GraphStyle == "Overlaid" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nccaseplot), Align="centre")
}

# TWO CAT - seperate,  categorial x
if(CaseProfilesPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==FALSE)
{
	HTML.title("<bf> ", HR=2, align="left")
	add<-c("As the Y-axis is non-numeric, no graph has been produced. Please review your selection.")
	HTML.title(add, HR=0, align="left")
}
if(CaseProfilesPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	dd<-data.frame(with(statdata, statdata[order(as.factor(statdata$catfact), eval(parse(text = paste("statdata$", CaseIDFactor))), eval(parse(text = paste("statdata$", XAxisVar)))), ]))
	nrow=dim(dd)[1]
	colours<-c(unique(levels(as.factor(dd$catfact)))[1])
	j=2
	k=1
	for ( i in 1:(nrow-1))
	{
		if (eval(parse(text = paste("dd$", CaseIDFactor)))[i+1]!=eval(parse(text = paste("dd$", CaseIDFactor)))[i] )
		{
			if(dd$catfact[i+1]==dd$catfact[i])
			{
				colours[j]=unique(levels(as.factor(dd$catfact)))[k]
				j=j+1
			} else {
				k=k+1
				colours[j]=unique(levels(as.factor(dd$catfact)))[k]
				j=j+1
			}
		}
	}
	col<-c(1)
	for (i in 1:length(colours))
	{
		for (j in 1:length(unique(levels(as.factor(dd$catfact)))))
		{
			if (colours[i] == unique(levels(as.factor(dd$catfact)))[j])
			{
				col[i]=j
			}
		}
	}
	anim<-c(1)
	j<-1
	for ( i in 1:(nrow-1))
	{
		if (eval(parse(text = paste("dd$", CaseIDFactor)))[i+1]==eval(parse(text = paste("dd$", CaseIDFactor)))[i] )
		{
			anim[i+1]=j
		} else {
			j=j+1
			anim[i+1]=j
		}
	}
	dd2<-data.frame(cbind(dd,anim))
	#Plot
	nccaseplot <- sub(".html", "nccaseplot.jpg", htmlFile)
	jpeg(nccaseplot)
	lev<-c(1:length(unique(levels(as.factor(statdata$catfact)))))
	par(las=1)
	p<-xyplot(eval(parse(text = paste("dd2$", YAxisVars)))~eval(parse(text = paste("dd2$", XAxisVar)))|as.factor(eval(parse(text = paste("dd2$", FirstCatFactor))))*as.factor(eval(parse(text = paste("dd2$", SecondCatFactor)))), groups=dd2$anim, type="o", data=dd, strip=strip.custom(style=1, bg="grey95"), main=MainTitle,xlab=CPXAxisTitle, ylab = YAxisTitle)#, col=col,par.settings = list( superpose.line = list(col=lev, lwd = 1) ),auto.key = list(space = "right", text=(unique(levels(as.factor(statdata$catfact)))), points = FALSE, type="b", lines = T,cex=1))  
	if (ReferenceLine!="NULL")
	{
		update(p, panel=function(...)
		{
    		panel.xyplot(...)
    		panel.abline(h=ReferenceLine, col="black", lty=2, lwd=2)
		})
	} else {
		update(p, panel=function(...)
		{
    		panel.xyplot(...)
		})
	}
}
if(CaseProfilesPlot == "Y" && FirstCatFactor != "NULL" && SecondCatFactor != "NULL" && GraphStyle == "Separate" && is.numeric(eval(parse(text = paste("statdata$", YAxisVars))))==TRUE)
{
	void<-HTMLInsertGraph(GraphFileName=sub("[A-Z0-9a-z,:,\\\\]*App_Data[\\\\]","", nccaseplot), Align="centre")
}


HTMLbr()
HTML.title("<bf>R references", HR=2, align="left")

HTML.title("<bf> ", HR=2, align="left")
HTML.title("<bf>   
	R Development Core Team (2008). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. ISBN 3-900051-07-0, URL http://www.R-project.org.
	", HR=0, align="left") 

#lattice
HTML.title("<bf> ", HR=2, align="left")
HTML.title("<bf> 
	Deepayan Sarkar (2009). lattice: Lattice Graphics. R package version 0.17-22. http://CRAN.R-project.org/package=lattice
	", HR=0, align="left")


#plotrix
HTML.title("<bf> ", HR=2, align="left")
HTML.title("<bf> 
	Jim Lemon, Ben Bolker, Sander Oom, Eduardo Klein, Barry Rowlingson, Hadley Wickham and Anupam Tyagi (2007). plotrix: Various plotting functions. R package version 2.1-7.
	", HR=0, align="left")

#R2HTML
HTML.title("<bf> ", HR=2, align="left")
HTML.title("<bf>    
	Lecoutre, Eric (2003). The R2HTML Package. R News, Vol 3. N. 3, Vienna, Austria.
	", HR=0, align="left")

#Sciplot
HTML.title("<bf> ", HR=2, align="left")
HTML.title("<bf> 
	Manuel Morales, with code developed by the R Development Core Team, with general advice from the R-help listserv community and especially Duncan Murdoch. sciplot: Scientific Graphing Functions for Factorial Designs. R package version 1.0-3.
	", HR=0, align="left")



